package com.wonderful.compose.flow

import kotlinx.coroutines.delay
import kotlinx.coroutines.async
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlin.coroutines.cancellation.CancellationException

/**
 * Describe:
 *
 * @author Wonderful
 * @time 2025/9/9 15:12
 */
class FlowCancel{
    fun cancelFlow() = runBlocking {
        // Kotlin 协程的取消机制，本质是通过抛出 CancellationException 来 “通知” 协程终止。
        // 正常流程是：
        // 调用 scope.cancel() → 协程作用域内抛出 CancellationException
        // 协程检测到这个异常 → 主动结束执行
        launch {
            while (isActive){
                try {
                    println("do something")
                    delay(1000)
                } catch (e: Exception) {
                    // 取消方式一：
                    if (!isActive && e is CancellationException) {
                        throw CancellationException()
                    }
                    // 取消方式二：
                    //coroutineContext.ensureActive()
                    println("catch exception")
                }
            }
            // 取消方式三：delay 移出 try-catch
            // delay(1000)
        }
    }

    suspend fun fetchData() = runBlocking{
        val deferred = async{
            delay(1000)
            "data"

        }
        deferred.cancel()
        deferred.await()
    }

    // 最佳实践：
    fun bestPractice() = runBlocking{
        while (isActive){
            try {
                println("do something")
            } catch (e: Exception) {
               coroutineContext.ensureActive()
                handleError(e)
            }
            delay(1000)
        }
    }

    fun handleError(e: Exception){
        println("handle $e")
    }
}


